package com.zzty.taskapp.daoImpl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zzty.taskapp.common.DBUtil;
import com.zzty.taskapp.dao.QuestionDAO;
import com.zzty.taskapp.entity.Question;

public class QuestionDAOImpl implements QuestionDAO {

	public String getQuestionById(String questinid) {
		String questions = "";
		String sql = "select * from question where Id=?";
		PreparedStatement ps = DBUtil.getPreparedStatement(sql);
		try {
			ps.setString(1, questinid);
			ResultSet rs = ps.executeQuery();
			int i = 1;
			while (rs.next()) {

				questions =  rs.getString("Content") + "\r\n";
				
			}
			return questions;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

	}

	public List<Question> getAllQuestion() throws Exception {
		List<Question> questions = new ArrayList<Question>();
		String sql = "select * from question";
		PreparedStatement ps = DBUtil.getPreparedStatement(sql);
		ResultSet rs = ps.executeQuery();

		while (rs.next()) {
			Question question = new Question();
			question.setId(rs.getInt("id"));
			question.setSubject(rs.getString("subject"));
			question.setContent(rs.getString("content"));
			questions.add(question);
		}
		return questions;
	}

	public int[] addQuestions(String[] questions) throws Exception {
		int[] ids = new int[questions.length];
		if (questions.length > 0) {
			for (int i = 0; i < questions.length; i++) {
				String sql = "insert into question(id,content) values(?,?)";
				PreparedStatement ps = DBUtil.getPreparedStatement(sql);
				int id = getNextId();
				ids[i] = id;
				ps.setInt(1, id);
				ps.setString(2, questions[i]);
				ps.executeUpdate();
			}

		}
		return ids;

	}

	public int getNextId() throws Exception {
		int id = 0;
		String sql = "select max(id) from question";
		PreparedStatement ps = DBUtil.getPreparedStatement(sql);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			id = rs.getInt(1);
		}
		return id + 1;

	}

}
